package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties weChatProperties;
    private final UserMapper  userMapper;
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());

        // 如果openid为空，则抛出登录失败的异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 根据openid查询用户
        User user = userMapper.getByOpenid(openid);

        // 如果用户不存在，则创建一个新的用户
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 将新用户插入数据库
            userMapper.insert(user);
        }
        // 返回用户
        return user;
    }

    private String getOpenid(String code){
        // 创建一个Map，用于存储微信登录所需的参数
        Map<String, String> map = new HashMap<>();
        // 将微信的appid放入Map中
        map.put("appid", weChatProperties.getAppid());
        // 将微信的secret放入Map中
        map.put("secret", weChatProperties.getSecret());
        // 将用户登录时获取的code放入Map中
        map.put("js_code", code);
        // 将授权类型放入Map中
        map.put("grant_type", "authorization_code");
        // 使用HttpClientUtil发送GET请求，获取微信登录的返回结果
        String json= HttpClientUtil.doGet(WX_LOGIN,map);

        // 将返回结果转换为JSONObject
        JSONObject jsonObject = JSON.parseObject(json);
        // 从JSONObject中获取openid
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
